package com.pac.weixin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.tools.SmsTools;
import com.common.tools.StringTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.MsgKeyContent;
import com.common.util.PropertyUtils;
import com.common.util.SessionKeyContent;
import com.kuanrf.commons.weixin.api.WxService;
import com.kuanrf.commons.weixin.bean.WxJsapiSignature;
import com.kuanrf.commons.weixin.msg.bean.result.WxOAuth2AccessToken;
import com.pac.doctor.service.DoctorService;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.service.UserDetailService;
import com.pac.weixin.service.WeiXinService;

/**
 * 微信用户注册
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/weixin/register")
public class WxRegisterController {

	private static Logger logger = Logger.getLogger(WxRegisterController.class);

	@Autowired
	private UserDetailService userDetailService;

	@Autowired
	private DoctorService doctorService;

	@Autowired
	private WxService wxMpService;

	@Autowired
	private WeiXinService weiXinService;

	/**
	 * 完善用户信息
	 * 
	 * @param userDetailBean
	 *            用户明细信息
	 * @param openId
	 *            微信OpenID
	 * @param captcha
	 *            验证码
	 * @param comefrom
	 *            从哪进入注册页面
	 * 
	 *            gotoRegister：微信端点击注册菜单进入注册页面
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/register")
	public ModelAndView register(HttpServletRequest request,
			UserDetailBean userDetailBean, String openId, String captcha,
			String comefrom) {

		ModelAndView mov = new ModelAndView();

		HttpSession session = request.getSession();
		String captchaSession = (String) session
				.getAttribute(SessionKeyContent.SESSION_KEY_WX_REGISTER_CAPTCHA
						+ userDetailBean.getMobilePhone());

		logger.info("微信用户注册，MobilePhone："+userDetailBean.getMobilePhone()+",name:"+userDetailBean.getName());
		checkCaptcha(userDetailBean.getMobilePhone(), captcha, captchaSession);

		// 全局用户ID
		String userId = "";

		// 用户是否已经填写过资料，如果填写过就修改，如果没有填写过就新增
		if (StringTools.isNull(userDetailBean.getId())) {
			// 2插入用户明细信息
			userDetailBean.setUserId(userId);
			userDetailBean.setOpenId(openId);
			String userDetailId = userDetailService
					.addUserDetail(userDetailBean);
			mov.addObject("userhis", userDetailId);
		} else {
			/*
			 * 已经存在的用户， 更新用户明细信息
			 */
			userDetailService.updateUserDetail(userDetailBean);
		}

		// 3、跳转到选择医院界面
		if("M6".equals(comefrom))
		{
			mov.setViewName("/weixin/questionnaire/questionnaire53");
		}
		else
		{
			mov.setViewName("/weixin/hospital/hospitalSel");
		}
		mov.addObject("openId", openId);

		// 微信页面获取js-sdk授权
		try {
			String url = PropertyUtils.getValue("system.domain.url")
					+ "/weixin/register/register";

			String appId = PropertyUtils.getValue("weixin.appID");
			WxJsapiSignature jsSign = wxMpService.createJsapiSignature(url);

			String timestamp = String.valueOf(jsSign.getTimestamp());
			String nonceStr = jsSign.getNoncestr();
			String signature = jsSign.getSignature();

			mov.addObject("appId", appId);
			mov.addObject("timestamp", timestamp);
			mov.addObject("nonceStr", nonceStr);
			mov.addObject("signature", signature);

		} catch (Exception ex) {
			logger.error("微信页面授权出错，" + ex);
		}

		return mov;
	}

	/**
	 * 下发验证码
	 * 
	 * @param phoneno
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/captcha/send")
	@ResponseBody
	public Map<String, Object> sendCaptcha(HttpServletRequest request,
			String phoneno) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {

			HttpSession session = request.getSession();

			String captcha = String.valueOf(Math.random() * 10000);
			captcha = captcha.substring(0, captcha.indexOf("."));
			if (captcha.length() < 4) {
				for (int n = 0; n < (4 - captcha.length()); n++) {
					captcha = "0" + captcha;
				}
			}

			String smsContent = "您的验证码是：" + captcha
					+ "。欢迎注册“宽仁妇孺关怀PAC”，如非本人操作，可忽略此条信息。";
			SmsTools.sendsms(phoneno, smsContent);

			session.setAttribute(
					SessionKeyContent.SESSION_KEY_WX_REGISTER_CAPTCHA + phoneno,
					captcha);

			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, true);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, "短信验证码下发成功");
		} catch (LogicException ex) {
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, false);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG,
					ex.getMessage());
		} catch (Exception ex) {
			logger.error("微信注册，下发短信出错：" + ex);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, false);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG,
					"系统内部错误，请稍后再次");
		}

		return map;
	}

	/**
	 * 检查微信注册验证码
	 * 
	 * @param request
	 * @param phoneno
	 *            手机号
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/captcha/check")
	@ResponseBody
	public Map<String, Object> checkCaptcha(HttpServletRequest request,
			String phoneno, String captcha) {
		Map<String, Object> map = new HashMap<String, Object>();

		HttpSession session = request.getSession();
		String captchaSession = (String) session
				.getAttribute(SessionKeyContent.SESSION_KEY_WX_REGISTER_CAPTCHA
						+ phoneno);
		try {
			checkCaptcha(phoneno, captcha, captchaSession);
		} catch (LogicException ex) {
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, false);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG,
					ex.getMessage());
			return map;
		} catch (Exception ex) {
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, false);
			map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG,
					"验证码验证出错，请稍后再试");
			return map;
		}

		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, true);
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, "验证码验证通过");
		return map;
	}

	/**
	 * 检查微信验证码
	 * 
	 * @param phoneno
	 *            手机号
	 * @param captcha
	 *            验证码
	 * @param captchaSession
	 *            session中的验证码
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private boolean checkCaptcha(String phoneno, String captcha,
			String captchaSession) {
		if (StringTools.isNull(phoneno)) {
			logger.error("检查微信注册验证码出错，手机号为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "手机号为空");
		}

		if (StringTools.isNull(captcha)) {
			logger.error("检查微信注册验证码出错，验证码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "请填写验证码");
		}

		if (StringTools.isNull(captchaSession)) {
			logger.error("检查微信注册验证码出错，session中的验证码为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "验证码过期，请重新发送");
		}

		if (!captcha.equals(captchaSession)) {
			logger.error("检查微信注册验证码出错，验证码错误");
			throw new LogicException(ErrorNumber.LOGIC_EXCEPTION, "验证码错误");
		}

		return true;
	}

	/**
	 * 进入用户注册页面
	 * 
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/goto")
	@ResponseBody
	public ModelAndView toRegister(HttpServletRequest request) {
		ModelAndView mov = new ModelAndView();

		try {
			Map<String, String[]> map = request.getParameterMap();
			String wxCode = map.get("code")[0];
			WxOAuth2AccessToken autoToken = wxMpService
					.oauth2getAccessToken(wxCode);
			String openId = autoToken.getOpenId();

			
			// 检查是否填写明细信息，如果未填写用户明细信息，就进入注册页面
			UserDetailBean userDetail = userDetailService
					.findUserDetailByOpenId(openId);
			if (null == userDetail) {
				mov.setViewName("/weixin/register/register");
				mov.addObject("comefrom", "gotoRegister");
			} else {
				mov.addObject("userdetail", userDetail);
				// 进入用户信息编辑页面
				mov.setViewName("/weixin/register/registerEdit");
			}
			
			mov.addObject("openId", openId);

		} catch (LogicException ex) {
			logger.error("进入微信注册页面出错，" + ex);
		} catch (Exception ex) {
			logger.error("进入医生注册页面出错，" + ex);
		}

		return mov;
	}

	/**
	 * 修改用户注册信息
	 * 
	 * @param userDetailBean
	 * @param openId
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public ModelAndView editUser(UserDetailBean userDetailBean, String openId) {
		ModelAndView mov = new ModelAndView();

		userDetailService.updateUserDetail(userDetailBean);
		UserDetailBean userDetail = userDetailService
				.findUserDetailByOpenId(openId);
		mov.addObject("userdetail", userDetail);
		mov.addObject("openId", openId);
		mov.setViewName("/weixin/register/registerEdit");
		return mov;
	}

}
